# apps/users/models.py
from django.db import models
from django.db.models.signals import post_migrate
from django.dispatch import receiver
from django.contrib.auth.hashers import make_password

class User(models.Model):
    user_id = models.AutoField(primary_key=True) # 用户唯一标识

    username = models.CharField(max_length=255, unique=True)  # 用户名
    password = models.CharField(max_length=255)  # 密码

    email     = models.EmailField(null=True, blank=True)
    phone     = models.CharField(max_length=30, null=True, blank=True)
    reg_time  = models.DateTimeField(auto_now_add=True, null=True)

    role = models.CharField(max_length=50)  # 用户角色（管理员、普通用户）
    permission_level = models.IntegerField(default=0)  # 权限级别

    def __str__(self):
        return self.username

    class Meta:
        db_table = 'users'  # 自定义数据库表名

@receiver(post_migrate)
def create_initial_user(sender, **kwargs):
    if sender.name == 'apps.users':  # 确保只在 user 应用中运行
        if not User.objects.filter(username='admin').exists():
            # 创建初始管理员用户
            User.objects.create(
                username='admin',
                password='admin123',  # 使用 Django 的密码哈希方法
                email='admin@gmail.com',
                phone='13302888963',
                reg_time=None,  # 可以设置为 None 或者使用当前时间
                role='管理员',
                permission_level=10  # 假设管理员的权限级别为 10
            )
            print("Initial admin user created.")


    # 最低级用户（无查看、无控制）
    if not User.objects.filter(username='lowuser').exists():
        User.objects.create(
            username='lowuser',
            password='lowuser123',
            email='lowuser@qq.com',
            phone='13302888964',
            role='普通用户',
            permission_level=0
        )
        print("Initial lowuser (level 0) created.")

    # 中级用户（仅查看）
    if not User.objects.filter(username='miduser').exists():
        User.objects.create(
            username='miduser',
            password='miduser123',
            email='miduser@qq.com',
            phone='13302888965',
            role='普通用户',
            permission_level=1
        )
        print("Initial miduser (level 1) created.")

    # 高级用户（查看+控制）
    if not User.objects.filter(username='highuser').exists():
        User.objects.create(
            username='highuser',
            password='highuser123',
            email='highuser@qq.com',
            phone='13302888966',
            role='普通用户',
            permission_level=2
        )
        print("Initial highuser (level 2) created.")